######################################################################
#	makefile ģ�� (by lichuang)
#
######################################################################

###################��Ŀ·���ͳ�������#################################
DIR=$(shell pwd)
BIN_DIR=$(DIR)/bin
LIB_DIR=$(DIR)/lib
SRC_DIR=$(DIR)/src
INCLUDE_DIR=$(DIR)/include
OBJ_DIR=$(DIR)/obj
DEPS_DIR=$(DIR)/deps
DUMP_OBJ=$(BIN_DIR)/rv.dump
PROGRAM=$(BIN_DIR)/rv.elf
TAR_BIN=$(BIN_DIR)/rv.bin

###################obj文件############################################
EXTENSION=c
AMS := $(patsubst $(SRC_DIR)/%.s, $(OBJ_DIR)/%.o,$(wildcard $(SRC_DIR)/*.s))
OBJS:=$(patsubst $(SRC_DIR)/%.$(EXTENSION), $(OBJ_DIR)/%.o,$(wildcard $(SRC_DIR)/*.$(EXTENSION)))
OBJS+=$(AMS)
DEPS:=$(patsubst $(OBJ_DIR)/%.o, $(DEPS_DIR)/%.d, $(OBJS))
CODE :=
CODE +=$(wildcard $(SRC_DIR)/*.s)
CODE +=$(wildcard $(SRC_DIR)/*.c)
$(info $(DEPS))


###################includeͷ�ļ�·��##################################
INCLUDE=\
		-I$(INCLUDE_DIR)
		
###################lib�ļ���·��######################################

###################����ѡ�������###################################

COMPLIE:=riscv64-unknown-elf-
CC :=$(COMPLIE)gcc 
DUMP:=$(COMPLIE)objdump
OBJCP:=$(COMPLIE)objcopy

ARCH_BASE = rv32i
ABI_BASE = ilp32
RISCV_MARCH = $(ARCH_BASE)
ABI =$(ABI_BASE)

RISCV_MARCH := $(RISCV_MARCH)

ARCH_FLAGS = -march=$(RISCV_MARCH) -mabi=$(ABI) -mcmodel=medlow

CFLAGS +=$(ARCH_FLAGS)
CFLAGS += -Wl,-r -nostartfiles -nodefaultlibs -nostdlib -Lbuild/main  -Wl,-e,main -fno-common \
-fno-builtin-printf  -nodefaultlibs

LDFLAGS += -nostartfiles --specs=nano.specs -fno-common 

LINK_SCRIPT:=$(DIR)/ld/link.lds
#LINK_SCRIPT:=$(DIR)/link_sram_bs1.lds
LDFLAGS +=$(ARCH_FLAGS)
LDFLAGS += -Wl,-T $(LINK_SCRIPT)
LDFLAGS += -Wl,--gc-sections 
LDFLAGS += -Wl,--no-relax          


###################����Ŀ��###########################################
.PHONY: all clean rebuild

all:$(OBJS) 
	@echo $(DEPS_DIR)
	$(CC) -o $(PROGRAM) $(OBJS) $(LDFLAGS)  $(CFLAGS)
	$(OBJCP) $(PROGRAM) --strip-debug
	$(DUMP) -D -S $(PROGRAM) > $(DUMP_OBJ) 2>&1
	

$(DEPS_DIR)/%.d: $(SRC_DIR)/%.$(EXTENSION)
	$(CC) -MM $(INCLUDE) $(CFLAGS) $< | sed -e 1's,^,$(OBJ_DIR)/,' > $@

sinclude $(DEPS)

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.s
	$(CC) $< -o $@ -c $(CFLAGS) $(INCLUDE) 

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
	$(CC) $< -o $@ -c $(CFLAGS) $(INCLUDE) 
rebuild: clean all

clean:
	rm -rf $(OBJS) $(BIN_DIR)/* $(OBJ_DIR)/* $(DEPS_DIR)/*

